import React, { useState, useEffect } from 'react'
import { X, Plus } from 'lucide-react'
import { experimentPlanningAPI } from '../services/api'

const AddExperimentModal = ({ visible, onClose, onAdd, equipments }) => {
  const [formData, setFormData] = useState({
    project_name: '',
    equipment_id: '',
    experiment_type: '',
    enter_date: '',
    start_date: '',
    complete_date: '',
    end_date: '',
    experiment_report_name: ''
  })
  
  const [loading, setLoading] = useState(false)
  const [errors, setErrors] = useState({})

  // 试验类型选项
  const experimentTypes = [
    { value: '整星', label: '整星' },
    { value: '单机', label: '单机' },
    { value: '自建', label: '自建' }
  ]

  // 重置表单
  const resetForm = () => {
    setFormData({
      project_name: '',
      equipment_id: '',
      experiment_type: '',
      enter_date: '',
      start_date: '',
      complete_date: '',
      end_date: '',
      experiment_report_name: ''
    })
    setErrors({})
  }

  // 关闭弹窗时重置表单
  useEffect(() => {
    if (!visible) {
      resetForm()
    }
  }, [visible])

  // 表单验证
  const validateForm = () => {
    const newErrors = {}
    
    if (!formData.project_name.trim()) {
      newErrors.project_name = '项目名称不能为空'
    }
    
    if (!formData.equipment_id) {
      newErrors.equipment_id = '请选择设备'
    }
    
    if (!formData.experiment_type) {
      newErrors.experiment_type = '请选择试验类型'
    }
    
    if (!formData.enter_date) {
      newErrors.enter_date = '入场时间不能为空'
    }
    
    if (!formData.start_date) {
      newErrors.start_date = '开始时间不能为空'
    }
    
    if (!formData.complete_date) {
      newErrors.complete_date = '完成时间不能为空'
    }
    
    if (!formData.end_date) {
      newErrors.end_date = '出场时间不能为空'
    }
    
    // 时间逻辑验证
    if (formData.enter_date && formData.start_date && formData.enter_date > formData.start_date) {
      newErrors.start_date = '开始时间不能早于入场时间'
    }
    
    if (formData.start_date && formData.complete_date && formData.start_date > formData.complete_date) {
      newErrors.complete_date = '完成时间不能早于开始时间'
    }
    
    if (formData.complete_date && formData.end_date && formData.complete_date > formData.end_date) {
      newErrors.end_date = '出场时间不能早于完成时间'
    }
    
    setErrors(newErrors)
    return Object.keys(newErrors).length === 0
  }

  // 处理表单提交
  const handleSubmit = async (e) => {
    e.preventDefault()
    
    if (!validateForm()) {
      return
    }
    
    setLoading(true)
    
    try {
      // 找到选中的设备信息
      const selectedEquipment = equipments.find(eq => eq.id === parseInt(formData.equipment_id))
      
      // 构造提交数据，映射到后端字段
      const submitData = {
        project: formData.project_name,
        equipment: selectedEquipment?.id,
        experiment_type: formData.experiment_type,
        enter_date: formData.enter_date,
        start_date: formData.start_date,
        complete_date: formData.complete_date,
        end_date: formData.end_date,
        experiment_report_name: formData.experiment_report_name || formData.project_name,
        source: 'manual', // 手动录入
        is_adjustable: true // 手动添加的试验默认为可调整
      }
      
      console.log('📝 提交新试验数据:', submitData)
      
      // 调用API创建试验计划
      const response = await experimentPlanningAPI.experimentPlan.create(submitData)
      
      console.log('✅ 试验创建成功:', response)
      
      // 通知父组件添加成功
      if (onAdd) {
        onAdd({
          ...response,
          equipment: selectedEquipment,
          experiment_name: formData.project_name,
          enter: formData.enter_date,
          start: formData.start_date,
          complete: formData.complete_date,
          end: formData.end_date
        })
      }
      
      // 关闭弹窗
      onClose()
      
    } catch (error) {
      console.error('❌ 创建试验失败:', error)
      setErrors({ submit: '创建试验失败，请重试' })
    } finally {
      setLoading(false)
    }
  }

  // 处理输入变化
  const handleInputChange = (field, value) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }))
    
    // 清除对应字段的错误
    if (errors[field]) {
      setErrors(prev => {
        const newErrors = { ...prev }
        delete newErrors[field]
        return newErrors
      })
    }
  }

  if (!visible) return null

  return (
    <div style={{
      position: 'fixed',
      top: 0,
      left: 0,
      right: 0,
      bottom: 0,
      backgroundColor: 'rgba(0, 0, 0, 0.5)',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      zIndex: 9999
    }}>
      <div style={{
        backgroundColor: 'white',
        borderRadius: '8px',
        boxShadow: '0 10px 25px rgba(0, 0, 0, 0.3)',
        width: '100%',
        maxWidth: '600px',
        margin: '16px',
        maxHeight: '90vh',
        overflowY: 'auto'
      }}>
        {/* 弹窗头部 */}
        <div style={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          padding: '24px',
          borderBottom: '1px solid #e5e7eb'
        }}>
          <h2 style={{
            fontSize: '20px',
            fontWeight: '600',
            color: '#374151',
            display: 'flex',
            alignItems: 'center'
          }}>
            <Plus style={{ width: '20px', height: '20px', marginRight: '8px', color: '#2563eb' }} />
            添加试验计划
          </h2>
          <button
            onClick={onClose}
            style={{
              color: '#9ca3af',
              background: 'none',
              border: 'none',
              cursor: 'pointer',
              padding: '4px',
              borderRadius: '4px',
              transition: 'color 0.2s'
            }}
            onMouseOver={(e) => e.target.style.color = '#6b7280'}
            onMouseOut={(e) => e.target.style.color = '#9ca3af'}
          >
            <X style={{ width: '24px', height: '24px' }} />
          </button>
        </div>

        {/* 表单内容 */}
        <form onSubmit={handleSubmit} style={{
          padding: '24px',
          display: 'flex',
          flexDirection: 'column',
          gap: '16px'
        }}>
          {/* 项目名称 */}
          <div>
            <label style={{
              display: 'block',
              fontSize: '14px',
              fontWeight: '500',
              color: '#374151',
              marginBottom: '4px'
            }}>
              项目名称 <span style={{ color: '#ef4444' }}>*</span>
            </label>
            <input
              type="text"
              value={formData.project_name}
              onChange={(e) => handleInputChange('project_name', e.target.value)}
              style={{
                width: '100%',
                padding: '8px 12px',
                border: `1px solid ${errors.project_name ? '#ef4444' : '#d1d5db'}`,
                borderRadius: '6px',
                fontSize: '14px',
                outline: 'none'
              }}
              placeholder="请输入项目名称"
              onFocus={(e) => e.target.style.borderColor = '#2563eb'}
              onBlur={(e) => e.target.style.borderColor = errors.project_name ? '#ef4444' : '#d1d5db'}
            />
            {errors.project_name && (
              <p style={{ color: '#ef4444', fontSize: '12px', marginTop: '4px' }}>{errors.project_name}</p>
            )}
          </div>

          {/* 设备选择 */}
          <div>
            <label style={{
              display: 'block',
              fontSize: '14px',
              fontWeight: '500',
              color: '#374151',
              marginBottom: '4px'
            }}>
              设备名称 <span style={{ color: '#ef4444' }}>*</span>
            </label>
            <select
              value={formData.equipment_id}
              onChange={(e) => handleInputChange('equipment_id', e.target.value)}
              style={{
                width: '100%',
                padding: '8px 12px',
                border: `1px solid ${errors.equipment_id ? '#ef4444' : '#d1d5db'}`,
                borderRadius: '6px',
                fontSize: '14px',
                outline: 'none',
                backgroundColor: 'white'
              }}
              onFocus={(e) => e.target.style.borderColor = '#2563eb'}
              onBlur={(e) => e.target.style.borderColor = errors.equipment_id ? '#ef4444' : '#d1d5db'}
            >
              <option value="">请选择设备</option>
              {equipments.map(equipment => (
                <option key={equipment.id} value={equipment.id}>
                  {equipment.name || equipment.equipment_name}
                </option>
              ))}
            </select>
            {errors.equipment_id && (
              <p style={{ color: '#ef4444', fontSize: '12px', marginTop: '4px' }}>{errors.equipment_id}</p>
            )}
          </div>

          {/* 试验类型 */}
          <div>
            <label style={{
              display: 'block',
              fontSize: '14px',
              fontWeight: '500',
              color: '#374151',
              marginBottom: '4px'
            }}>
              试验类型 <span style={{ color: '#ef4444' }}>*</span>
            </label>
            <select
              value={formData.experiment_type}
              onChange={(e) => handleInputChange('experiment_type', e.target.value)}
              style={{
                width: '100%',
                padding: '8px 12px',
                border: `1px solid ${errors.experiment_type ? '#ef4444' : '#d1d5db'}`,
                borderRadius: '6px',
                fontSize: '14px',
                outline: 'none',
                backgroundColor: 'white'
              }}
              onFocus={(e) => e.target.style.borderColor = '#2563eb'}
              onBlur={(e) => e.target.style.borderColor = errors.experiment_type ? '#ef4444' : '#d1d5db'}
            >
              <option value="">请选择试验类型</option>
              {experimentTypes.map(type => (
                <option key={type.value} value={type.value}>
                  {type.label}
                </option>
              ))}
            </select>
            {errors.experiment_type && (
              <p style={{ color: '#ef4444', fontSize: '12px', marginTop: '4px' }}>{errors.experiment_type}</p>
            )}
          </div>

          {/* 时间字段 - 两列布局 */}
          <div style={{
            display: 'grid',
            gridTemplateColumns: '1fr 1fr',
            gap: '16px'
          }}>
            {/* 入场时间 */}
            <div>
              <label style={{
                display: 'block',
                fontSize: '14px',
                fontWeight: '500',
                color: '#374151',
                marginBottom: '4px'
              }}>
                入场时间 <span style={{ color: '#ef4444' }}>*</span>
              </label>
              <input
                type="date"
                value={formData.enter_date}
                onChange={(e) => handleInputChange('enter_date', e.target.value)}
                style={{
                  width: '100%',
                  padding: '8px 12px',
                  border: `1px solid ${errors.enter_date ? '#ef4444' : '#d1d5db'}`,
                  borderRadius: '6px',
                  fontSize: '14px',
                  outline: 'none'
                }}
                onFocus={(e) => e.target.style.borderColor = '#2563eb'}
                onBlur={(e) => e.target.style.borderColor = errors.enter_date ? '#ef4444' : '#d1d5db'}
              />
              {errors.enter_date && (
                <p style={{ color: '#ef4444', fontSize: '12px', marginTop: '4px' }}>{errors.enter_date}</p>
              )}
            </div>

            {/* 开始时间 */}
            <div>
              <label style={{
                display: 'block',
                fontSize: '14px',
                fontWeight: '500',
                color: '#374151',
                marginBottom: '4px'
              }}>
                开始时间 <span style={{ color: '#ef4444' }}>*</span>
              </label>
              <input
                type="date"
                value={formData.start_date}
                onChange={(e) => handleInputChange('start_date', e.target.value)}
                style={{
                  width: '100%',
                  padding: '8px 12px',
                  border: `1px solid ${errors.start_date ? '#ef4444' : '#d1d5db'}`,
                  borderRadius: '6px',
                  fontSize: '14px',
                  outline: 'none'
                }}
                onFocus={(e) => e.target.style.borderColor = '#2563eb'}
                onBlur={(e) => e.target.style.borderColor = errors.start_date ? '#ef4444' : '#d1d5db'}
              />
              {errors.start_date && (
                <p style={{ color: '#ef4444', fontSize: '12px', marginTop: '4px' }}>{errors.start_date}</p>
              )}
            </div>

            {/* 完成时间 */}
            <div>
              <label style={{
                display: 'block',
                fontSize: '14px',
                fontWeight: '500',
                color: '#374151',
                marginBottom: '4px'
              }}>
                完成时间 <span style={{ color: '#ef4444' }}>*</span>
              </label>
              <input
                type="date"
                value={formData.complete_date}
                onChange={(e) => handleInputChange('complete_date', e.target.value)}
                style={{
                  width: '100%',
                  padding: '8px 12px',
                  border: `1px solid ${errors.complete_date ? '#ef4444' : '#d1d5db'}`,
                  borderRadius: '6px',
                  fontSize: '14px',
                  outline: 'none'
                }}
                onFocus={(e) => e.target.style.borderColor = '#2563eb'}
                onBlur={(e) => e.target.style.borderColor = errors.complete_date ? '#ef4444' : '#d1d5db'}
              />
              {errors.complete_date && (
                <p style={{ color: '#ef4444', fontSize: '12px', marginTop: '4px' }}>{errors.complete_date}</p>
              )}
            </div>

            {/* 出场时间 */}
            <div>
              <label style={{
                display: 'block',
                fontSize: '14px',
                fontWeight: '500',
                color: '#374151',
                marginBottom: '4px'
              }}>
                出场时间 <span style={{ color: '#ef4444' }}>*</span>
              </label>
              <input
                type="date"
                value={formData.end_date}
                onChange={(e) => handleInputChange('end_date', e.target.value)}
                style={{
                  width: '100%',
                  padding: '8px 12px',
                  border: `1px solid ${errors.end_date ? '#ef4444' : '#d1d5db'}`,
                  borderRadius: '6px',
                  fontSize: '14px',
                  outline: 'none'
                }}
                onFocus={(e) => e.target.style.borderColor = '#2563eb'}
                onBlur={(e) => e.target.style.borderColor = errors.end_date ? '#ef4444' : '#d1d5db'}
              />
              {errors.end_date && (
                <p style={{ color: '#ef4444', fontSize: '12px', marginTop: '4px' }}>{errors.end_date}</p>
              )}
            </div>
          </div>

          {/* 试验项目名称 */}
          <div>
            <label style={{
              display: 'block',
              fontSize: '14px',
              fontWeight: '500',
              color: '#374151',
              marginBottom: '4px'
            }}>
              试验项目名称
            </label>
            <input
              type="text"
              value={formData.experiment_report_name}
              onChange={(e) => handleInputChange('experiment_report_name', e.target.value)}
              style={{
                width: '100%',
                padding: '8px 12px',
                border: '1px solid #d1d5db',
                borderRadius: '6px',
                fontSize: '14px',
                outline: 'none'
              }}
              placeholder="可选，默认使用项目名称"
              onFocus={(e) => e.target.style.borderColor = '#2563eb'}
              onBlur={(e) => e.target.style.borderColor = '#d1d5db'}
            />
          </div>

          {/* 提交错误信息 */}
          {errors.submit && (
            <div style={{
              color: '#ef4444',
              fontSize: '14px',
              backgroundColor: '#fef2f2',
              padding: '12px',
              borderRadius: '6px'
            }}>
              {errors.submit}
            </div>
          )}

          {/* 按钮组 */}
          <div style={{
            display: 'flex',
            justifyContent: 'flex-end',
            gap: '12px',
            paddingTop: '16px',
            borderTop: '1px solid #e5e7eb'
          }}>
            <button
              type="button"
              onClick={onClose}
              style={{
                padding: '8px 16px',
                color: '#4b5563',
                backgroundColor: 'white',
                border: '1px solid #d1d5db',
                borderRadius: '6px',
                cursor: 'pointer',
                fontSize: '14px',
                transition: 'background-color 0.2s'
              }}
              disabled={loading}
              onMouseEnter={(e) => !loading && (e.target.style.backgroundColor = '#f9fafb')}
              onMouseLeave={(e) => !loading && (e.target.style.backgroundColor = 'white')}
            >
              取消
            </button>
            <button
              type="submit"
              style={{
                padding: '8px 16px',
                backgroundColor: loading ? '#93c5fd' : '#2563eb',
                color: 'white',
                border: 'none',
                borderRadius: '6px',
                cursor: loading ? 'not-allowed' : 'pointer',
                fontSize: '14px',
                opacity: loading ? 0.5 : 1,
                transition: 'background-color 0.2s',
                display: 'flex',
                alignItems: 'center'
              }}
              disabled={loading}
              onMouseEnter={(e) => !loading && (e.target.style.backgroundColor = '#1d4ed8')}
              onMouseLeave={(e) => !loading && (e.target.style.backgroundColor = '#2563eb')}
            >
              {loading ? (
                <>
                  <div style={{
                    width: '16px',
                    height: '16px',
                    border: '2px solid white',
                    borderTop: '2px solid transparent',
                    borderRadius: '50%',
                    animation: 'spin 1s linear infinite',
                    marginRight: '8px'
                  }}></div>
                  创建中...
                </>
              ) : (
                <>
                  <Plus style={{ width: '16px', height: '16px', marginRight: '8px' }} />
                  创建试验
                </>
              )}
            </button>
          </div>
        </form>
      </div>
    </div>
  )
}

export default AddExperimentModal